package com.archive.starter.config;

import com.archive.core.ArchiveContext;
import com.archive.core.config.ArchiveProperties;
import com.archive.core.constants.ArchiveStrategy;
import com.archive.core.util.Assert;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
public class ArchiveConfig {

    @Bean
    public ArchiveContext archiveContext(ArchiveProperties archiveProperties, ApplicationContext applicationContext) throws SQLException, IllegalAccessException {
        ArchiveContext archiveContext = new ArchiveContext(archiveProperties);
        String dataSourceRef = archiveProperties.getDataSourceRef();
        Assert.notNull(dataSourceRef, () -> "dataSourceRef is required");
        DataSource dataSource = applicationContext.getBean(dataSourceRef, DataSource.class);
        Assert.notNull(dataSource, () -> "dataSource is required");
        archiveContext.setDataSource(dataSource);

        if (ArchiveStrategy.BACKUP == archiveProperties.getArchiveStrategy()) {
            String targetDataSourceRef = archiveProperties.getTargetDataSourceRef();
            Assert.notNull(targetDataSourceRef, () -> "targetDataSourceRef is required");
            DataSource targetDataSource = applicationContext.getBean(targetDataSourceRef, DataSource.class);
            Assert.notNull(targetDataSource, () -> "dataSource is required");
            archiveContext.setTargetDataSource(targetDataSource);
        }

        archiveContext.init();

        return archiveContext;
    }

    @Bean
    @ConfigurationProperties(prefix = "archive")
    public ArchiveProperties archiveProperties() {
        return new ArchiveProperties();
    }

}
